package com.dc.project.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.annotation.DataScope;
import com.dc.common.constant.CustomSqlConstants;
import com.dc.common.constant.DataScopeConstants;
import com.dc.common.exception.ServiceException;
import com.dc.common.utils.PageUtil;
import com.dc.common.utils.StringUtil;
import com.dc.common.vo.ResultVo;
import com.dc.project.system.dao.SysRoleDao;
import com.dc.project.system.dto.SysRoleDto;
import com.dc.project.system.dto.SysUserRoleDto;
import com.dc.project.system.entity.SysRole;
import com.dc.project.system.entity.SysUserRole;
import com.dc.project.system.service.SysRoleDeptService;
import com.dc.project.system.service.SysRoleMenuService;
import com.dc.project.system.service.SysRoleService;
import com.dc.project.system.service.SysUserRoleService;
import com.dc.project.system.vo.SysUserRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统角色表(SysRole)表服务实现类
 *
 * @author zhuangcy
 * @since 2021-06-01 14:30:43
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRole> implements SysRoleService {
    @Autowired
    private SysRoleDeptService sysRoleDeptService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return
     */
    @Override
    public ResultVo queryById(Serializable id) {
        return ResultVo.success().data(this.getById(id));
    }

    /**
     * 分页查询系统角色表
     *
     * @param dto
     * @return
     */
    @DataScope
    @Override
    public ResultVo queryByPage(SysRoleDto dto) {
        QueryWrapper<SysRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByDesc(SysRole::getCreatedTime);
        IPage<SysRole> page = this.page(PageUtil.convert2PageParam(dto), queryWrapper);
        return ResultVo.success().data(PageUtil.convert2PageResult(page));
    }

    /**
     * 新增系统角色表
     *
     * @param sysRole
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo add(SysRole sysRole) {
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRole::getRoleCode, sysRole.getRoleCode())
                .last(CustomSqlConstants.LIMIT_1);
        SysRole one = this.getOne(queryWrapper);
        if (null != one) {
            throw new ServiceException(StringUtil.format("{}该编码已存在", sysRole.getRoleCode()));
        }
        sysRole.setDataScope(DataScopeConstants.DATA_SCOPE_SELF);
        return ResultVo.verify(this.save(sysRole));
    }

    /**
     * 编辑系统角色表
     *
     * @param sysRole
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo edit(SysRole sysRole) {
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRole::getRoleCode, sysRole.getRoleCode())
                .last(CustomSqlConstants.LIMIT_1);
        SysRole one = this.getOne(queryWrapper);
        if (null != one && !one.getRoleId().equals(sysRole.getRoleId())) {
            throw new ServiceException(StringUtil.format("{}该编码已存在", sysRole.getRoleCode()));
        }
        return ResultVo.verify(this.updateById(sysRole));
    }

    /**
     * 根据主键删除系统角色表
     *
     * @param id 主键
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo delete(Integer id) {
        // 删除时校验角色是否已被使用
        if (sysUserRoleService.existUser(id)) {
            return ResultVo.failed().msg("该角色已被使用，无法删除");
        }
        return ResultVo.verify(this.removeById(id));
    }

    /**
     * 根据用户id获取用户角色列表
     *
     * @param userId
     * @return
     */
    @Override
    public ResultVo getUserRole(Integer userId) {
        List<SysUserRoleVo> list = baseMapper.getUserRoleByUserId(userId);
        return ResultVo.success().data(list);
    }

    /**
     * 分页查询根据用户获取用户角色列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResultVo getUserRolePage(SysRoleDto dto) {
        IPage page = PageUtil.convert2PageParam(dto);
        IPage<SysRole> pageList = baseMapper.getUserRolePage(page, dto);
        return ResultVo.success().data(PageUtil.convert2PageResult(pageList));
    }

    /**
     * 编辑系统角色权限
     *
     * @param sysRole
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo editRoleMenuDept(SysRoleDto sysRole) {
        List<Integer> deptIds = sysRole.getDeptIds();
        List<Integer> menuIds = sysRole.getMenuIds();
        if (DataScopeConstants.DATA_SCOPE_CUSTOM.equals(sysRole.getDataScope()) && deptIds.isEmpty()) {
            return ResultVo.failed().msg("未选择组织权限");
        }
        if (menuIds.isEmpty()) {
            return ResultVo.failed().msg("未选择菜单权限");
        }
        SysRole role = new SysRole();
        role.setDataScope(sysRole.getDataScope());
        role.setRoleId(sysRole.getRoleId());
        if (this.updateById(role)) {
            if (!deptIds.isEmpty() && !sysRoleDeptService.addBatchRoleDept(sysRole.getRoleId(), deptIds)) {
                throw new ServiceException("组织权限添加失败");
            }
            if (!sysRoleMenuService.addBatchRoleMenu(sysRole.getRoleId(), menuIds)) {
                throw new ServiceException("菜单权限添加失败");
            }
            return ResultVo.success();
        }
        throw new ServiceException();
    }

    /**
     * 获取用户角色
     *
     * @param dto
     * @return
     */
    @Override
    public ResultVo getUserRoleList(SysUserRoleDto dto) {
        List<SysRole> roles = this.list();
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, dto.getUserId());
        List<Integer> roleIds = sysUserRoleService.list(queryWrapper).stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        HashMap<String, Object> result = new HashMap<>(2);
        result.put("roles", roles);
        result.put("roleIds", roleIds);
        return ResultVo.success().data(result);
    }

}